package com.tronsis.distribution.activity.me.points;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.PointsWithdrawBean;
import com.tronsis.distribution.bean.PointsWithdrawLogBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class MyPointsActivity extends ToolBarBaseActivity {

    @BindView(R.id.rb_frozen)
    RadioButton mRbFrozen;
    @BindView(R.id.rb_detail)
    RadioButton mRbDetail;
    @BindView(R.id.rg_point)
    RadioGroup mRgPoint;
    @BindView(R.id.rv_point_frozen)
    RecyclerView mRvPointFrozen;
    @BindView(R.id.rv_point_detail)
    RecyclerView mRvPointDetail;
    @BindView(R.id.tv_my_points)
    TextView mTvMyPoints;
    private CommonAdapter<PointsWithdrawBean> mFrozenAdapter;
    private List<PointsWithdrawBean> mFrozenList = new ArrayList<>();

    private CommonAdapter<PointsWithdrawLogBean> mDetailAdapter;
    private List<PointsWithdrawLogBean> mDetailList = new ArrayList<>();

    private int mFrozenPage = 1;
    private int mFrozenSize = 15;
    private int mFrozenTotal;
    private LoadMoreWrapper mFrozenLoadMoreWrapper;

    private int mDetailPage = 1;
    private int mDetailSize = 15;
    private int mDetailTotal;
    private LoadMoreWrapper mDetailLoadMoreWrapper;
    private ImageItem mImageItem = new ImageItem();
    private CommonAdapter<ImageItem> mPayImageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_points);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.my_integral), getString(R.string.withdrawal));

        initView();
        httpPointsWithDraw(mFrozenPage, mFrozenSize, true);
        httpGetMyPoints();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if ((requestCode == 100 || requestCode == 200) && resultCode == RESULT_OK) {
            httpPointsWithDraw(mFrozenPage, mFrozenSize, true);
        }
    }

    private void initView() {
        mRgPoint.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_frozen:
                        mRvPointFrozen.setVisibility(View.VISIBLE);
                        mRvPointDetail.setVisibility(View.GONE);
                        httpPointsWithDraw(mFrozenPage, mFrozenSize, true);
                        break;
                    case R.id.rb_detail:
                        mRvPointFrozen.setVisibility(View.GONE);
                        mRvPointDetail.setVisibility(View.VISIBLE);
                        httpPointsWithDrawLog(mDetailPage, mDetailSize, true);
                        break;
                    default:
                        break;
                }
            }
        });

        mTvMyPoints.setText(String.valueOf(UserBizFactory.createBiz().getLoginUser(this).getPoints()));

        mFrozenAdapter = new CommonAdapter<PointsWithdrawBean>(mContext, mFrozenList, R.layout.item_point_frozen) {
            @Override
            protected void convert(ViewHolder holder, PointsWithdrawBean pointsWithdrawBean, final int position) {
                Button grievanceButton = holder.getView(R.id.btn_point_grievance);

                LinearLayout mllPpayImage = holder.getView(R.id.ll_pay_image);
                RecyclerView mRvPpayImage = holder.getView(R.id.rv_pay_image);
                Button deleteButton = holder.getView(R.id.btn_point_delete);
                Button completeButton = holder.getView(R.id.btn_point_confirm);
                holder.setText(R.id.tv_time, DateUtil.getDateTimeString(pointsWithdrawBean.getStateOn()));
                String state = pointsWithdrawBean.getState();
                holder.setText(R.id.tv_type, StateUtil.getPointsState(mContext, state));
                holder.setText(R.id.tv_points, getString(R.string.format_ask_points, String.valueOf(pointsWithdrawBean.getPoint())));
                holder.setText(R.id.tv_point_price, getString(R.string.format_amount, pointsWithdrawBean.getPointPrice()));
                ArrayList<ImageItem> allList = new ArrayList<>();
                ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(pointsWithdrawBean.getPaymentFid());
                allList.addAll(splitImage);

                switch (state) {
                    case StateUtil.STATE_PAY: //待付款
                        completeButton.setVisibility(View.GONE);
                        deleteButton.setVisibility(View.GONE);
                        grievanceButton.setVisibility(View.VISIBLE);
                        mllPpayImage.setVisibility(View.GONE);
                        break;
                    case StateUtil.STATE_CONFIRM://待确认
                        completeButton.setVisibility(View.VISIBLE);
                        deleteButton.setVisibility(View.GONE);
                        grievanceButton.setVisibility(View.VISIBLE);
                        mllPpayImage.setVisibility(View.VISIBLE);
                        SetImageRv(mRvPpayImage, allList);
                        break;
                    case StateUtil.STATE_REPORT: //申诉中
                        completeButton.setVisibility(View.GONE);
                        deleteButton.setVisibility(View.GONE);
                        grievanceButton.setVisibility(View.GONE);
                        mllPpayImage.setVisibility(View.VISIBLE);
                        SetImageRv(mRvPpayImage, allList);
                        break;
                    case StateUtil.STATE_FINISH://已完成
                        completeButton.setVisibility(View.GONE);
                        deleteButton.setVisibility(View.VISIBLE);
                        grievanceButton.setVisibility(View.GONE);
                        mllPpayImage.setVisibility(View.VISIBLE);
                        SetImageRv(mRvPpayImage, allList);
                        break;
                    default:
                        break;
                }

                grievanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, PointGrievanceActivity.class);
                        intent.putExtra("withdrawId", mFrozenList.get(position).getId());
                        startActivityForResult(intent, 200);
                    }
                });

                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
                            @Override
                            public void onLeftButtonClick(View view) {

                            }

                            @Override
                            public void onRightButtonClick(View view) {
                                httpDeleteFinishPointWithDraw(mFrozenList.get(position).getId());
                            }
                        }).showDialog("确认删除？", "取消", "确定");
                    }
                });

                completeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
                            @Override
                            public void onLeftButtonClick(View view) {

                            }

                            @Override
                            public void onRightButtonClick(View view) {
                                httpConfirmPointWithDraw(mFrozenList.get(position).getId());
                            }
                        }).showDialog("确认提现完成？", "取消", "确定");
                    }
                });

            }
        };

        mFrozenAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mFrozenLoadMoreWrapper = new LoadMoreWrapper(mFrozenAdapter);
        mFrozenLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mFrozenLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mFrozenList.size() % 15 == 0 && mFrozenList.size() > 0 && mFrozenList.size() < mFrozenTotal) {
                    mFrozenPage = (mFrozenList.size() / 15) + 1;
                    httpPointsWithDraw(mFrozenPage, mFrozenSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvPointFrozen.addItemDecoration(decoration);
        mRvPointFrozen.setLayoutManager(new LinearLayoutManager(mContext));
        mRvPointFrozen.setAdapter(mFrozenLoadMoreWrapper);


        mDetailAdapter = new CommonAdapter<PointsWithdrawLogBean>(mContext, mDetailList, R.layout.item_point_detail) {
            @Override
            protected void convert(ViewHolder holder, PointsWithdrawLogBean pointsWithdrawLogBean, int position) {

                //ONTRIBUTE(贡献奖励), SALES(销售奖励), WITHDRAW(提现), DELIVERY(运费抵扣), RESOURCE(素材奖励), PAY_WITHDRAW(支付下级提现), REFUND_WITHDRAW(提现超时退还), DEPOSIT_CHANGE(押金变动), PURCHASE(进货), TO_AGENT(转代理), UPGRADE(代理升级)
                String state = pointsWithdrawLogBean.getType();
                String symbol = "";
                if (pointsWithdrawLogBean.getAmount() > 0) {
                    symbol = "+";
                }

                holder.setText(R.id.tv_type_points, getString(R.string.format_type_points, StateUtil.getLogState(mContext, state), symbol, String.valueOf(pointsWithdrawLogBean.getAmount())));
                holder.setText(R.id.tv_createdOn, DateUtil.getDateTimeString(pointsWithdrawLogBean.getCreatedOn()));

            }
        };

        mDetailAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mDetailLoadMoreWrapper = new LoadMoreWrapper(mDetailAdapter);
        mDetailLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mDetailLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDetailList.size() % 15 == 0 && mDetailList.size() > 0 && mDetailList.size() < mDetailTotal) {
                    mDetailPage = (mDetailList.size() / 15) + 1;
                    httpPointsWithDrawLog(mDetailPage, mDetailSize, false);
                }
            }
        });
        int height2 = DisplayUtil.getInstance(mContext).dp2px(1);
        int color2 = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration2 = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height2, color2);

        mRvPointDetail.addItemDecoration(decoration2);
        mRvPointDetail.setLayoutManager(new LinearLayoutManager(mContext));
        mRvPointDetail.setAdapter(mDetailLoadMoreWrapper);
    }

    private void SetImageRv(RecyclerView mRvPpayImage, final ArrayList<ImageItem> allList) {

        mPayImageAdapter = new CommonAdapter<ImageItem>(mContext, allList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }
                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }
                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(allList.get(position).path) && TextUtils.isEmpty(allList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, allList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });
            }
        };


        mRvPpayImage.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvPpayImage.setAdapter(mPayImageAdapter);
        mRvPpayImage.setHasFixedSize(true);
        mRvPpayImage.setNestedScrollingEnabled(false);
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:
                Intent intent = new Intent(mContext, WithdrawalActivity.class);
                startActivityForResult(intent, 100);
                break;
        }
    }

    private void httpDeleteFinishPointWithDraw(String withdrawId) {
        try {
            UserBizFactory.createBiz().deleteFinishPointWithDraw(this, withdrawId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    httpPointsWithDraw(mFrozenPage, mFrozenSize, true);
                    httpGetMyPoints();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });

        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpConfirmPointWithDraw(String withdrawId) {
        try {
            UserBizFactory.createBiz().confirmPointWithDraw(this, withdrawId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    httpPointsWithDraw(mFrozenPage, mFrozenSize, true);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });

        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


    private void httpPointsWithDraw(int page, int size, final boolean isRefresh) {
        try {

            UserBizFactory.createBiz().getPointsWithDraw(this, page, size, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mFrozenTotal = listBean.getTotal();
                    List<PointsWithdrawBean> list = listBean.getList();
                    if (isRefresh) {
                        mFrozenList.clear();
                        mFrozenList.addAll(list);
                    } else {
                        mFrozenList.addAll(list);
                    }
                    mFrozenLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void httpPointsWithDrawLog(int page, int size, final boolean isRefresh) {
        try {

            UserBizFactory.createBiz().getPointsWithDrawLog(this, page, size, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mDetailTotal = listBean.getTotal();
                    List<PointsWithdrawLogBean> list = listBean.getList();
                    if (isRefresh) {
                        mDetailList.clear();
                        mDetailList.addAll(list);
                    } else {
                        mDetailList.addAll(list);
                    }
                    mDetailLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpGetMyPoints() {
        try {
            UserBizFactory.createBiz().getMyPoint(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    Integer points = (Integer) data;
                    if (points != null) {
                        mTvMyPoints.setText(String.valueOf(points));
                        UserBean userBean = UserBizFactory.createBiz().getLoginUser(MyPointsActivity.this);
                        userBean.setPoints(points);
                        DBUtil.getInstance(MyPointsActivity.this).save(userBean);

                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
